var wcmp = require('../wechat/index').wcmp;

var memberServiceNative = require("../services/memberService.js");
var storeServiceNative = require("../services/storeService.js");
var memberAccountServiceNative = require("../services/MemberAccountService");
var memberPointsServiceNative = require("../services/MemberPointsService");
var memberTypeServiceNative = require("../services/MemberTypeService");
var merchantServiceNative = require("../services/MerchantService");
var idHelper = require("../common/utils/id-helper");
var async = require("async");
var moment = require("moment");
var wechat = require('../wechat/mp/index')
var errorHandler = require('../common/errorHandler');

var msiteController = {
	bind: function (member, req, cb) {
		cb(null, null);
		//memberServiceNative.bind(req.params.storeId, member, req.body.sns, null, function (err, result) {
		//	req.query.code = null;
		//	cb(err, result);
		//});
	},
	getBoundMember: function (sns, openId, req, cb) {
		memberServiceNative.getMemberById(req.session['memberId'], cb);
	}
}

var otherSnsController = {
	bind: function (member, req, cb) {
		console.log('openid-------' + req.body.openId);
		console.log(member);
		if (req.body.openId == undefined || req.body.openId == 'undefined') {
			return cb({code: 450});
		}
		memberServiceNative.bind(req.params.storeId, member, req.body.sns, req.body.openId, function (err, result) {
			if (err) {
				return cb(err);
			}
			req.query.code = req.body.code;
			cb();
		});
	},
	getBoundMember: function (sns, openId, req, cb) {
		memberServiceNative.getUserByOpenId(sns, openId, cb);
	}
}

function snsController(sns) {
	return sns == 'mstore' ? msiteController : otherSnsController;
}

var memberController = {
	info: function (req, res, next) {
		var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
		var memberAccountService = errorHandler.errorToResponse(req, res, memberAccountServiceNative);
		var memberPointsService = errorHandler.errorToResponse(req, res, memberPointsServiceNative);

		var memberInfo = {member: req.appParams.member, store: req.appParams.store, code: req.appParams.code, sns: req.appParams.sns};
		async.series([
			//member account
			function (cb) {
				memberAccountService.getAccount(req.appParams.member, function (err, account) {
					memberInfo.account = account;
					cb(err, account);
				})
			},
			//member points
			function (cb) {
				memberPointsService.getPoints(req.appParams.member, function (err, points) {
					memberInfo.points = points;
					cb(err, points);
				})
			},
			//member last order
			function (cb) {
				memberService.getLastOrder(req.appParams.member, function (err, lasOrder) {
					memberInfo.lasOrder = lasOrder;
					cb(err, lasOrder);
				})
			},
			//member inventory
			function (cb) {
				memberService.getInventory(req.appParams.member, 0, 3, function (err, inventories) {
					memberInfo.inventories = inventories;
					cb(err, inventories);
				})
			}
		], function (err, result) {
			res.send(memberInfo);
		})
	},

	binding: function (req, res, next) {
		res.render('member/binding.html', {
			name: '绑定',
			code: req.query.code,
			sns: req.query.sns,
			back: req.query.back,
			storeId: req.params.storeId
		});
	},
	bind: function (req, res, next) {
		var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
		var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
		if (!req.session['verficationInfo']) {
			return res.status(400).json({error: '已超时请重新获取动态登录密码！'});
		}
		if (req.session['verficationInfo'].code != req.body.verficationCode) {
			return res.status(400).json({error: '动态登录密码错误'});
		}
		var storeId = '';
		var memberInfo = {};
		async.series([
			function (cb) {
				storeService.getStoreByDomainName(req.params.storeId, function (err, settings) {
					if (!settings) {
						return res.status(400).json({error: '该店铺没有生成微店铺'});
					}
					storeId = settings.store_id;
					req.params.storeId = storeId;
					cb(null, storeId);
				})
			}, function (cb) {
				memberService.getMemberByAccount(storeId, req.body.account, function (err, member) {
					if (err) {
						return res.status(400).json({error: '没有该会员'});
					}
					if (!member) {
						return res.status(400).json({error: '没有该会员'});
					}
					snsController(req.body.sns).bind(member, req, function (err, data) {

						if (err) {
							if (err.code == 450) {
								return res.status(400).json({'error': '未获取到微信信息，请重新绑定微信公共帐号！'});
							} else {
								return res.status(400).json({'error': '绑定错误，请重新获取登录密码！'});
							}
						}
						res.send(member);
						cb(err, member);
					});
				});
			}
		], function (err, data) {
		})

	},
	sendSMS: function (req, res, next) {
		var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
		var merchantService = errorHandler.errorToResponse(req, res, merchantServiceNative);

		var mobile = req.body.account;
		var storeId = req.params.storeId;
		if (!idHelper.isMobile(mobile)) {
			return res.send({error: {message: '手机号无法识别', code: "is_not_mobile"}});
		}
		memberServiceNative.getMemberByAccount(storeId, mobile, function (err, data) {
			if (err) {
				return res.status(400).json({error: '参数错误'});
			}
			if (!data) {
				return res.status(400).json({error: '您非本店会员'});
			}
			var code = '';
			var newVerficationCodeTime = new Date().getTime();

			if (!req.session['verficationInfo']) {
				code = idHelper.verficationCode();
			} else {
				var time = req.session['verficationInfo'].startTime + 5 * 60 * 1000;
				if (time < newVerficationCodeTime) {
					code = idHelper.verficationCode();
				} else {
					newVerficationCodeTime = req.session['verficationInfo'].startTime;
					code = req.session['verficationInfo'].code;
				}
				if (req.session['verficationInfo'].mobile != mobile) {
					code = idHelper.verficationCode();
				}
			}
			var merchant = {};
			var merchantId = '';
			async.series([
				function (cb) {
					storeService.getStoreById(storeId, null, function (err, store) {
						if (err) {
							return res.status(400).json({error: "参数错误"});
						}
						merchantId = store.merchant_id;
						cb(err, store);
					})
				},
				function (cb) {
					merchantService.getMerchantById(merchantId, function (err, merchantData) {
						if (err) {
							return res.status(400).json({error: "参数错误"});
						}
						merchant = merchantData;
						cb(err, merchantData)
					})
				}
			], function (err, result) {
				if (process.env.NODE_ENV == 'test') {
					req.session['verficationInfo'] = {code: code, mobile: mobile, startTime: newVerficationCodeTime};
					console.log("你的会员手机号：" + mobile + "绑定验证码：" + code);
					return res.send({message: "验证码发送成功"});
				} else {
					storeService.sendSMSToMember(code, mobile, merchant, function (err, data) {
						console.log('send msg ok');
						req.session['verficationInfo'] = {code: code, mobile: mobile, startTime: newVerficationCodeTime};
						return res.send({message: "验证码发送成功"});
					})
				}
			})
		})
	},
	filter: function (req, res, next) {
		var self = this;
		var sns = req.query.sns || 'msite';

		function openIdGot(err, openId) {
			req.session['openId_' + code] = openId;
			snsController(sns).getBoundMember(sns, openId, req, function (err, member) {
				if (!member) {
					res.redirect('../member-bind/binding?sns=' + sns + '&code=' + code + '&back=' + encodeURIComponent(req.originalUrl));
					return;
				}
				req.appParams = {};
				req.appParams.member = member;
				req.appParams.sns = sns;
				req.appParams.code = code;
				next();
			});
		}

		//oauth返回的改用户验证code
		var code = req.query.code;
		if (req.session['openId_' + code]) {
			return openIdGot(null, req.session['openId_' + code]);
		}
		//根据code获取openID
		if (process.env.NODE_ENV == 'test') {
			return openIdGot(null, code);
		}
		wcmp.oauth.getAccessToken(code, function (err, result) {
			if (err) {
				openIdGot(err);
				return;
			}
			openIdGot(null, result.data.openid);
		});
	},
	memberInfo: function (req, res, next) {
		var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
		var memberAccountService = errorHandler.errorToResponse(req, res, memberAccountServiceNative);
		var memberPointsService = errorHandler.errorToResponse(req, res, memberPointsServiceNative);
		var memberTypeService = errorHandler.errorToResponse(req, res, memberTypeServiceNative);

		var memberInfo = {};

		var memberId = req.params.id
		if (memberId == 'undefined') {
			res.status(400).json({error: '参数错误'});
			return;
		}
		async.series([
			function (cb) {
				memberService.getMemberById(memberId, function (err, member) {
					memberInfo.member = member;
					cb(err, member);
				})
			},//获取类型
			function (cb) {
				memberTypeService.getTypeById(memberInfo.member.membertype_id, function (err, memberType) {
					memberInfo.memberType = memberType;
					cb(err, memberType);
				})
			},//获取到点次数
			function (cb) {
				memberService.toStoreTime(memberInfo.member.id, memberInfo.member.mgmtdomain, function (err, time) {
					memberInfo.toStoreTime = time;
					cb(err, time);
				})
			},
			//member account
			function (cb) {
				memberAccountService.getAccount(memberInfo.member.id, function (err, account) {
					if (!account) {
						account = {balance: 0};
					}
					memberInfo.account = account;
					cb(err, account);
				})
			},
			//member points
			function (cb) {
				memberPointsService.getPoints(memberInfo.member.id, function (err, points) {
					if (!points) {
						points = {points: 0};
					}
					memberInfo.points = points;
					cb(err, points);
				})
			},
			//member last order
			function (cb) {
				memberService.getLastOrder(memberInfo.member, function (err, lasOrder) {
					memberInfo.lasOrder = lasOrder;
					cb(err, lasOrder);
				})
			},
			//member inventory
			function (cb) {
				memberService.getInventory(memberInfo.member, 0, 3, function (err, inventories) {
					memberInfo.inventories = inventories;
					cb(err, inventories);
				})
			}
		], function (err, result) {
			res.send(memberInfo);
		})
	},
	memberOneInfo: function (req, res, next) {
		var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
		var memberTypeService = errorHandler.errorToResponse(req, res, memberTypeServiceNative);

		var memberInfo = {};

		var memberId = req.params.id
		async.series([
			function (cb) {
				memberService.getMemberById(memberId, function (err, member) {
					memberInfo.member = member;
					cb(err, member);
				})
			},//获取类型
			function (cb) {
				memberTypeService.getTypeById(memberInfo.member.membertype_id, function (err, memberType) {
					memberInfo.memberType = memberType;
					cb(err, memberType);
				})
			},//获取到点次数
		], function (err, result) {
			res.send(memberInfo);
		})
	},
	changePassword: function (req, res, next) {
		var memberId = req.params.id;
		var pwd = req.body.pwd;
		if (!pwd) {
			res.status(400).json('密码不能为空');
		}
		memberServiceNative.updatePassword(pwd, memberId, function (err, data) {
			if (err) return res.status(400).json(err);
			return res.send();
		})
	},
	getPayReq: function (req, res, next) {
		var memberId = req.params.id;
		var storeId = req.query.storeId;
		if (!memberId || !storeId) {
			res.status(400).json('参数不多');
		}
		memberAccountServiceNative.getPayReq(memberId, storeId, function (err, data) {
			if (err) return res.status(400).json(err);
			return res.send(data);
		})
	},
	updatePayReq: function (req, res, next) {
		var operToken = req.query.openToken;
		var reqId = req.params.reqId;
		var payReq = {};
		var tx = {};
		var accountData = {};
		async.series([function (cb) {
			memberAccountServiceNative.getPayReqById(reqId, function (err, data) {
				payReq = data;
				if (err) {
					return res.status(400).json(err);
				}
				if (!data) {
					return res.status(400).json('支付请求已经过期，请店员重新发起微会员支付。');
				}
				if (operToken != payReq.oper_token) {
					return res.status(400).json('支付请求已经过期，请重新刷新页面');
				}
				payReq.status = 'closed';
				payReq.operToken = new Date().getTime();
				cb(err, data)
			});
		}, function (cb) {
			memberAccountServiceNative.pay(payReq, function (err, okData) {
				if (err) return res.status(400).json(err);
				cb(err, okData);
			});
		}, function (cb) {
			memberAccountServiceNative.getAccount(payReq.payer_id, function (err, account) {
				if (err) return res.status(400).json(err);
				accountData = account;
				tx.id = idHelper.createId();
				tx.amount = 0 - payReq.amount;
				tx.createTime = tx.txTime = moment().format('YYYY-MM-DD HH:mm:ss');
				tx.memberAccount = payReq.payer_id;
				tx.orderNo = payReq.order_id;
				tx.subChannel = "mstorepay";
				tx.member = payReq.payer_id;
				tx.txType = 'pay';
				tx.txTime = tx.createTime;
				tx.balance = account.balance;
				tx.store = JSON.stringify({"id": payReq.store_id});
				accountData.balance = account.balance + tx.amount;
				cb(null);
			});

		}, function (cb) {
			memberAccountServiceNative.updateTx(tx, function (err, data) {
				if (err) return res.status(400).json(err);
				cb(err, data);
			})
		}, function (cb) {
			memberAccountServiceNative.updateAccount(accountData, function (err, data) {
				if (err) return res.status(400).json(err);
				cb(err, data);
			})
		}
		], function (err, result) {
			return res.send(payReq);
		})

	}

};


module.exports = memberController;